# -*- coding: UTF-8 -*-

# emoticons.py
#
#  Copyright (c) 2007 INdT (Instituto Nokia de Technologia)
#                2007 Kenneth Rohde Christiansen
#
#  Author: Kenneth Rohde Christiansen <kenneth.christiansen@gmail.com>
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License as
#  published by the Free Software Foundation; either version 2 of the
#  License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
#  USA

import pygtk
pygtk.require("2.0")
import gtk
import gobject
import os
import math
from xdg.BaseDirectory import load_data_paths
from emoticon_dialog import EmoticonDialog

class Emoticons(gobject.GObject):


    def __init__(self):
        self.emotes = {}
        self.emotes_group = {}

        self.load_emoticon_theme()


    def get_emoticon_infos_from_group(self, group):
        """
        Returns a list of entries in the form of ('smile.png', [':-)', ':)']).
        """

        return self.emotes_group[group]


    def get_group_names(self):
        """
        Returns the names of the groups of emoticons, like MSN,
        Gtalk, Yahoo, etc.
        """

        groups = []

        for group in self.emotes_group:
            groups.append(group)

        return groups


    def get_emoticon_pixbufs(self, reload=False):
        """
        Returns a dictionary of pixbufs indexed by the emoticon tag, ie. ':-)'

        In case, the dictionary is to be reloaded or it is empty, all the 
        emoticons from the groups, default, MSN and Gtalk are added to 
        self.emotes as self.emotes[':-)'] -> pixbuf
        """

        if len(self.emotes) == 0 or reload == True:
            for group in self.emotes_group:
                if group == "default" or group == "GTalk" or group == "MSN":
                    for (filename, emote_tags) in self.emotes_group[group]:
                        for emote_tag in emote_tags:
                            if emote_tag != "":
                                full_path = load_data_paths("ereseva", "emoticons", "16x16", filename).next()
                                pixbuf = gtk.gdk.pixbuf_new_from_file(full_path)
                                self.emotes[emote_tag] = pixbuf

        return self.emotes


    def load_emoticon_theme(self):
        """
        Reads the emoticon index.theme file and build up a hash containing all 
        emoticons (self.emotes_group[group]) in the form of ('smile.png', 
        [':-)', ':)']). 
        """
        emotes_themes = load_data_paths("ereseva", "emoticons", "index.theme")
        emotes_theme = emotes_themes.next()

        if not emotes_theme:
            raise UserWarning("no ereseva icon themes found in /usr/share,\
                    /usr/local/share, or $XDG_DATA_DIRS")

        emotes_dir = os.path.dirname(emotes_theme)

        group = None

        if os.path.exists(emotes_theme):
            theme_file = open(emotes_theme, 'r')

            for line in theme_file.readlines():
                pure_line = line.strip()

                if pure_line.startswith("[") and pure_line.endswith("]"):
                    group = pure_line[1:-1]

                    self.emotes_group[group] = []
                elif group != None:
                    sline = pure_line.split(" ")

                    if sline[0].endswith(".png") and not sline[0].startswith("#"):
                        filename = sline[0]
                        emote_tags = sline[1:]

                        self.emotes_group[group].append((filename, emote_tags))

            theme_file.close()


    def get_emoticon_menu(self, text_buffer):
        """
        Return a squared menu containing the default emoticons.
        """

        menu = gtk.Menu()

        def emoticon_clicked(widget, emoticon_tag):
            end_iter = text_buffer.get_end_iter()
            text_buffer.insert(end_iter, emoticon_tag)

        def on_more_clicked(widget):
            self.emoticon_dialog = EmoticonDialog(self, text_buffer)

            response = self.emoticon_dialog.run()

            if response == gtk.RESPONSE_CLOSE:
                self.emoticon_dialog.destroy()


        emoticon_pixbufs = self.get_emoticon_pixbufs()
        default_emoticon_info = self.get_emoticon_infos_from_group("default")

        size = int(round(math.sqrt(len(default_emoticon_info))))

        counter = 0

        for info in default_emoticon_info:
            item = gtk.MenuItem()
            image = gtk.Image()

            # pick the first
            emoticon_tag = info[1][0]

            image.set_from_pixbuf(emoticon_pixbufs[emoticon_tag])
            item.add(image)
            item.connect('activate', emoticon_clicked, emoticon_tag)

            menu.attach(item, counter % size, counter % size + 1, \
                        counter / size, counter / size + 1)
            counter = counter + 1

        item = gtk.MenuItem()
        item.add(gtk.Label("More"))
        item.connect('activate', on_more_clicked)
        menu.attach(item, 0, size, size + 1, size + 2)

        menu.show_all()

        return menu
